require_relative 'xml_helpers'


module CSDNConfig
	module PostBuild

		class Artifacts
			include XMLHelpers

			def initialize(*args)
				opts = args.last.is_a?(Hash) ? args.pop : {}

				@artifacts = args
				@keep_all = opts.has_key?(:keep) ? opts[:keep] : false
			end

			def latest_only_string
				@keep_all ? 'false' : 'true'
			end

			def to_xml
				apply_template :archive_artifacts
			end
		end

		class CreateGitTag < Struct.new(:tag_name,:tag_message)
			include XMLHelpers

			def to_xml
				apply_template :git_tag
			end
		end

		class CodeCoverageReport < Struct.new(:report_file)
			include XMLHelpers

			def to_xml
				apply_template :cobertura_coverage_report
			end
		end


		# Upload one or more files to release server
		# Specify destination subdirectory with :subdir option
		# Supports specifying individual files or local globs
		#
		# Example: FTPUpload.new('a/file.jar', 'b/*.jar', 'c/another_file.xml', subdir: 'some/subpath')
		class FTPUpload
			include XMLHelpers
			
			def initialize(*args)
				opts = args.last.is_a?(Hash) ? args.pop : {}
				@destSubDir = opts[:subdir] || ''
				@targets = args.map {|arg| _ftp_target arg}
			end

			def destination_directory
				ftpURL = ENV['FTP_URL'] or raise "FTP_URL environment variable must be defined!"
				dir = File.join ftpURL, @destSubDir
				dir += '/' unless dir.end_with? '/'
				dir
			end

			def to_xml
				apply_template :ftp_upload
			end

			def _ftp_target target
				# target could be not yet created, so here we introduce ?d as a directory identifier
				# if you want to upload a directory to ftp, suggest to end the directory with ?d
				if File.directory? target or target.end_with? '?d'
					if target.end_with? '?d'
						target = target.chomp('?d')
					end
					@command = <<GLOB_COMMAND
static_suffix=.a
dynamic_suffix=.so
for x in `find #{target} -type f`; do
	if [[ $x == *$static_suffix || $x == *$dynamic_suffix ]]; then
		curl --ftp-create-dirs -T $x -u $credentials $dest
	else
		new_x=${x##{target}}
		curl --ftp-create-dirs -T $x -u $credentials $dest$new_x
	fi
done
GLOB_COMMAND
				elsif target.include? '*' # glob
					@command = <<GLOB_COMMAND
for x in #{target}; do
  curl --ftp-create-dirs -T $x -u $credentials $dest
done
GLOB_COMMAND
				else
					@command = <<SINGLE_FILE
curl --ftp-create-dirs -T #{target} -u $credentials $dest
SINGLE_FILE
				end
			end

		end


		class CleanWorkspace
			include XMLHelpers

			def to_xml
				apply_template :clean_workspace
			end
		end
		
	end
end

if __FILE__ == $0

	ftpUpload = CSDNConfig::PostBuild::FTPUpload.new('target/*.jar', subdir: 'test/release')
	puts ftpUpload.to_xml
end

